<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="设计师昵称" prop="designerName">
        <el-input v-model="queryParams.designerName" placeholder="请输入设计师昵称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="方案名称" prop="schemeName">
        <el-input v-model="queryParams.schemeName" placeholder="请输入方案名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" plain icon="Plus" @click="handleAdd" v-hasPermi="['decor:schem:add']">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="schemList" row-key="schemeId" default-expand-all :tree-props="{ children: 'updateRecord' }">
      <el-table-column label="ID" align="center" prop="schemeId" :show-overflow-tooltip="true" />
      <el-table-column label="设计师昵称" align="center" prop="designerName" :show-overflow-tooltip="true" />
      <el-table-column label="方案名称" align="center" prop="schemeName" :show-overflow-tooltip="true" />
      <el-table-column label="设计理念" align="center" prop="designIdea" :show-overflow-tooltip="true" />
      <el-table-column label="封面图" align="center" prop="url" width="100" :show-overflow-tooltip="true">
        <template #default="scope">
          <ImagePreview :src="scope.row.url" :width="50" :height="50" :preview-src-list="[scope.row.url]" />
        </template>
      </el-table-column>
      <el-table-column label="小区名称" align="center" prop="address" :show-overflow-tooltip="true" />
      <el-table-column label="面积(㎡)" align="center" prop="area" :show-overflow-tooltip="true" />
      <el-table-column label="参考预算价(万元)" align="center" prop="priceLower" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>¥{{ parseFloat(scope.row.priceLower) / 10000 }} ~ ¥{{ parseFloat(scope.row.priceUpper) / 10000 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="风格" align="center" prop="style" :show-overflow-tooltip="true" />
      <el-table-column label="审核状态" align="center" prop="schemStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="schem_status" :value="scope.row.schemStatus" />
        </template>
      </el-table-column>
      <el-table-column label="排序" :show-overflow-tooltip="true" align="center" prop="sort1">
        <template #default="scope">
          <div>{{ scope.row.sort1 }}</div>
          <el-button link type="warning" size="small" @click="editSort(scope.row)"
            v-hasPermi="['decor:schem:edit']">修改排序</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="150px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['decor:schem:edit']">修改</el-button>
          <el-button link type="warning" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['decor:schem:remove']">删除</el-button>
          <el-button link type="primary" v-show="scope.row.schemStatus === 1 || scope.row.schemStatus === 3"
            :icon="scope.row.schemStatus === 3 ? 'Upload' : 'Download'" size="small" @click="handleDownload(scope.row)"
            v-hasPermi="['decor:schem:edit']">{{
              scope.row.schemStatus === 3 ?
              '上架' : '下架' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script setup>
import { listSchem, delSchem, updateStatusSchem } from "@/api/decor/schem";
import ImagePreview from "@/components/ImagePreview/index.vue";
import { getImgUrl } from "@/api/decor/designer";
const { proxy } = getCurrentInstance();
const { schem_status } = proxy.useDict('schem_status');
const router = useRouter();
// 表格数据
const schemList = ref([]);
// 遮罩层
const loading = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schemeName: null,
    designerName: null,
    // orderByColumn: 'decor_schem.scheme_id',
    // isAsc: 'desc'
  },
});

const { queryParams } = toRefs(data);
/** 查询设计方案列表 */
function getList() {
  loading.value = true;
  listSchem(queryParams.value).then(response => {
    let imgUrlPromises = [];
    let data = response.rows.map((v) => {
      return { ...v, url: '' }
    })
    data.forEach((v) => {
      // 每次循环创建一个 Promise，并将其推入数组
      if (v.coverImage) {
        let promise = getImgUrl(v.coverImage).then((res) => {
          v.url = res.data[0].url;
        });
        imgUrlPromises.push(promise);
      }
      if (v.updateRecord.length > 0) {
        if (v.updateRecord[0].coverImage) {
          let avatarPromise = getImgUrl(v.updateRecord[0].coverImage).then((res) => {
            v.updateRecord[0].url = res.data[0].url;
          });
          imgUrlPromises.push(avatarPromise);
        }
      }
    })
    Promise.all(imgUrlPromises).then(() => {
      // 所有的异步操作完成后再更新 designerList.value
      schemList.value = data;
      total.value = response.total;
      loading.value = false;
    });
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 新增按钮操作
function handleAdd() {
  router.push("/designScheme/editDesignScheme");
}

// 修改按钮操作
function handleUpdate(row) {
  router.push("/designScheme/editDesignScheme/" + row.schemeId);
}
// 调整排序
const editSort = (row) => {
  proxy.$prompt('请输入"' + row.schemeName + '"的排序', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^(?:[1-9][0-9]{0,3})$/,
    inputErrorMessage: "请输入介于 1 和 9999 之间的数字",
  }).then(({ value }) => {
    const data = {
      schemeId: row.schemeId,
      sort1: value,
      version: row.version
    }
    updateStatusSchem(JSON.stringify(data)).then(response => {
      proxy.$modal.msgSuccess("修改排序成功");
      getList()
    });
  }).catch(() => { });
}
// 删除按钮操作
function handleDelete(row) {
  const _schemeIds = row.schemeId;
  proxy.$modal.confirm('是否确认删除设计方案为"' + row.schemeName + '"的数据？').then(function () {
    return delSchem(_schemeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
// 下架操作
const handleDownload = (row) => {
  const status = row.schemStatus === 3 ? '上架' : '下架'
  const schemStatus = row.schemStatus === 3 ? 1 : 3
  proxy.$modal.confirm(`是否确认${status}设计方案"' ${row.schemeName}'"？`).then(function () {
    return updateStatusSchem(JSON.stringify({
      schemeId: row.schemeId,
      schemStatus: schemStatus,
      version: row.version
    }));
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(`${status}成功`);
  }).catch(() => { });
}
getList();
</script>
